package com.countertack.endtoendstories;

import java.io.File;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.sql.ResultSet;
import java.util.UUID;

import org.doublecloud.vi.vmware.guest.GuestProcessDirector;

import com.countertack.impala.ImpalaConnector;
import com.countertack.ssh.SSHManager;
import com.countertack.utils.Configuration;
import com.countertack.utils.HttpClientUtils;
import com.countertack.vmware.VMWareConnector;
import com.countertack.vmware.VMWareUtils;
import com.vmware.vim25.mo.VirtualMachine;

public class VerifyingEvents {
	public static void main(String[] args) throws Exception {
		String vmUser = null;
		String vmPassword = null;

//		if (args.length <= 0) {
//
//			System.out.println("configuration details missed !");
//			return;
//		}
//		String configFilePath = args[0];
		String configFilePath="C:\\Users\\user\\Desktop\\endtoendautomation\\config.properties";
		StringBuffer testCaseResult = new StringBuffer();
		
		String uuid = UUID.randomUUID().toString();
		Configuration.loadProperties(configFilePath);
		vmUser = Configuration.getProperty("vmuser");
		vmPassword = Configuration.getProperty("vmpassword");
		InetAddress address = InetAddress.getByName(Configuration
				.getProperty("sentinelehost"));
		String sentenelIp = address.getHostAddress();
		System.out.println(address.getHostAddress());
		// connect to hadoop impala

		ImpalaConnector iConnector;

		iConnector = ImpalaConnector
				.createImpalaConnectorInstance(Configuration
						.getProperty("sentinelehost"));

		// connect to esxi and starting virtual machines

		VMWareConnector esxiConnector = new VMWareConnector(
				Configuration.getProperty("esxi"));
		// poweredOn
		final VirtualMachine endPointMachine = esxiConnector
				.getVirtualMachineByname(Configuration.getProperty("vmname"));
		System.out.println("power state >>>"
				+ endPointMachine.getRuntime().powerState);

		String endpointMachineStatus = null;

		
		String smokeSnapShotName = Configuration
				.getProperty("rootsnapshotname");
		esxiConnector.revertToSnapShort(endPointMachine.getSnapshot()
				.getRootSnapshotList(), smokeSnapShotName);

		System.out.println("Reverting to root snap shot>>>>>"
				+ smokeSnapShotName);

		Thread.sleep(180000);

		endpointMachineStatus = esxiConnector
				.getVirtualMachineStatus(endPointMachine);

		if (endpointMachineStatus == null) {

			System.out.println("Power on  endpoint machine .....");

			esxiConnector.startVirtualMachine(endPointMachine);

			Thread.sleep(600000);

		} else {

			if ("notRunning".equalsIgnoreCase(endpointMachineStatus)) {

				esxiConnector.reStartVirtualMachine(endPointMachine);

				System.out.println("Rebooting endpoint machine .....");

				Thread.sleep(600000);

			}

		}
		
		
boolean isXpmachine=false;
		
		String osType = VMWareUtils.getVMOSArchitecture(
				Configuration.getProperty("esxi"),
				Configuration.getProperty("vmname"));
		
		if (osType != null) {

			osType = osType.toLowerCase();

			if (osType.contains("xp")) {

				isXpmachine = true;
			}
		}
		GuestProcessDirector progDir = new GuestProcessDirector(
				endPointMachine, vmUser, vmPassword);
		

		if (isXpmachine) {

			progDir.run("C:\\Windows\\System32\\cmd.exe",
					"/c copy C:\\Windows\\System32\\cmd.exe \"C:\\Documents and Settings\\"
							+ vmUser + "\\cmd.exe\"");
		} else {

			progDir.run("C:\\Windows\\System32\\cmd.exe",
					"/c copy C:\\Windows\\System32\\cmd.exe C:\\Users\\"
							+ vmUser + "\\cmd.exe");
		}
		

			
		
		
		// initialising ssh to virtual machines

		System.out.println("ip>>>" + endPointMachine.getGuest().ipAddress);

		final SSHManager endpointSsh = new SSHManager(vmUser, vmPassword,
				endPointMachine.getGuest().ipAddress);
		endpointSsh.connect();

		// install agent

		// install agent
testCaseResult.append("Sentinel IP>>>>"+sentenelIp+"\n");
testCaseResult.append("VM IP>>>>"+endPointMachine.getGuest().ipAddress+"\n");
		endpointSsh.copyFile(Configuration.getProperty("driverpath"),
				"CounterTack Agent Installer Hiding.exe");

		if (isXpmachine) {
			endpointSsh
					.runCommand("cmd /c \"C:\\Documents and Settings\\"
							+ vmUser
							+ "\\CounterTack Agent Installer Hiding.exe\" /S /HOST:"
							+ sentenelIp + " /PORT:443");

		} else {

			endpointSsh
					.runCommand("cmd /c \"C:\\Users\\"
							+ vmUser
							+ "\\CounterTack Agent Installer Hiding.exe\" /S /HOST:"
							+ sentenelIp + " /PORT:443");

		}

		System.out.println("Installing agent on endpoint");
		Thread.sleep(300000);
		

		String eId = null;
		ResultSet endpointIdRes = iConnector
				.executeQueryAndReturnResults("select id from endpoints where ip='"
						+ endPointMachine.getGuest().ipAddress
						+ "'"
						+ " and status='ON' and ip is not null order by time_started desc limit 1");

		while (endpointIdRes.next()) {
			try {
				eId = endpointIdRes.getString(1);
			} catch (Exception e) {

			}

			System.out.println("endpoint Id>>>>>>" + eId);
			testCaseResult.append("endpoint Id>>>>>>" + eId + "\n");

		}

		if (eId == null) {

			System.out.println("endpoint is not installed");
			testCaseResult.append("endpoint is not installed");
			addResultsToLog(testCaseResult);
			System.exit(0);

		}
		String driverVersion=getDriverVersion(eId, iConnector);
		testCaseResult.append("Kernal Module Version>>>>"+driverVersion+"\n");
		

		pauseEndpoint(eId);
		Thread.sleep(60000);

		
		
		resumeEndpoint(eId);
		Thread.sleep(60000);

		if (isXpmachine) {
			progDir.run(
					"C:\\Documents and Settings\\" + vmUser + "\\cmd.exe",
					"/c ipconfig > \"c:\\Documents and Settings\\"
							+ vmUser
							+ "\\vmwaretest1.txt\" && sc query && arp -a && echo \"hello world\" > \"c:\\Documents and Settings\\"
							+ vmUser
							+ "\\testfile"
							+ uuid
							+ ".txt\" && reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\smoketestkey_"
							+ uuid);

		} else {
			progDir.run(
					"C:\\Users\\" + vmUser + "\\cmd.exe",
					"/c ipconfig > c:\\Users\\"
							+ vmUser
							+ "\\vmwaretest1.txt && sc query && arp -a && echo \"hello world\" >  c:\\Users\\"
							+ vmUser
							+ "\\testfile"
							+ uuid
							+ ".txt && reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\smoketestkey_"
							+ uuid);

		}

	

	Thread.sleep(120000);

		ResultSet brs = iConnector
				.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
						+ eId + "%'  order by event_start_time desc limit 1");
		String bhid = null;

		while (brs.next()) {
			bhid = brs.getString(1);

		}
		// System.out.println("behavior id>>>>" + bhid);

		// verifying netcat client
		
		/*
		ResultSet netcatpros = iConnector
				.executeQueryAndReturnResults("select target_process_name from behaviors_denorm where hex(behavior_id)='"
						+ bhid
						+ "' and behavior_id is not null and is_origin=1");*/
	
		ResultSet netcatpros = iConnector
				.executeQueryAndReturnResults("select target_process_name from behaviors_denorm where hex(behavior_id)='"
						+ bhid
						+ "' and behavior_id is not null");
		boolean inbound = false;
		while (netcatpros.next()) {
			String path = netcatpros.getString(1);

			if (path != null) {

				// System.out.println("path>>>" + path);
				if (path.contains("cmd.exe")) {

					// System.out.println("Inbound passed");
					inbound = true;
					break;
					// System.exit(0);
					// return;

				}

			}
		}

		if (inbound) {

			System.out.println("New origin event---------->Pass");
			testCaseResult
					.append("New origin Event---------->Pass \n");

		} else {

			System.out.println("New origin event---------->Fail");
			testCaseResult
					.append("New origin event---------->Fail \n");

		}
		ResultSet flwrrs = iConnector
				.executeQueryAndReturnResults("select target_file_path from behaviors_denorm where hex(behavior_id) = '"
						+ bhid
						+ "' and behavior_id is not null group by target_file_path");
		boolean fwrite = false;
		while (flwrrs.next()) {
			String fn = flwrrs.getString(1);

			if (fn != null) {

				System.out.println("fname>>>" + fn);
				if (fn.contains("testfile" + uuid + ".txt")) {

					// System.out.println("Inbound passed");
					fwrite = true;
					break;
					// System.exit(0);
					// return;

				}

			}
		}

		if (fwrite) {

			System.out.println("New Key event for file write------->Pass");
			testCaseResult
					.append("New Key event for file write------->Pass \n");

		} else {

			System.out.println("New Key event for file write------->Fail");
			testCaseResult
					.append("New Key event for file write------->Fail \n");

		}

		addResultsToLog(testCaseResult);

	}

	public static void addResultsToLog(StringBuffer vals) {
		File testCaseResFile = new File("Verify_events_result_"
				+ Configuration.getProperty("vmname") + ".txt");

		try {
			testCaseResFile.createNewFile();
			FileOutputStream fout = new FileOutputStream(testCaseResFile);

			//

			fout.write(vals.toString().getBytes());

			fout.flush();
			fout.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	public static void pauseEndpoint(String eid) throws Exception {

		String pause = "{ " + "  \"type\":\"pause_many\", "
				+ "  \"endpoints\":[ " + "\"" + eid + "\" " + " ] " + "} ";

		HttpClientUtils
				.composePostRequest(
						"https://s13.dev.countertack.com:9090/api/v1/endpoints/command",
						pause);

	}

	public static void resumeEndpoint(String eid) throws Exception {

		String resume = "{ " + "  \"type\":\"resume_many\", "
				+ "  \"endpoints\":[ " + "    \"" + eid + "\" " + "] " + "} ";

		HttpClientUtils
				.composePostRequest(
						"https://s13.dev.countertack.com:9090/api/v1/endpoints/command",
						resume);

	}
	public static String getDriverVersion(String eid, ImpalaConnector iConnector) {

		String driver_Version = null;
		ResultSet endpointStatRes = iConnector
				.executeQueryAndReturnResults("select driver_version from endpoints where id='"
						+ eid + "'");
		try {
			while (endpointStatRes.next()) {
				try {
					driver_Version = endpointStatRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println("Driver version>>>>>>" + driver_Version);

			}
		} catch (Exception e) {

		}

		return driver_Version;

	}

}
